package com.cse.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cse.dto.LoginFormDTO;
import com.cse.dto.Result;
import com.cse.dto.UserDTO;
import com.cse.entity.User;
import com.cse.mapper.UserMapper;
import com.cse.service.IUserService;
import com.cse.utils.RegexUtils;
import com.cse.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.cse.constants.RedisConstants.*;
import static com.cse.constants.SystemConstants.*;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result signCount() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        //凭借key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keySuffix;
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取本月已经签到的天数返回一个十进制
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            return Result.ok(0);
        }
        Long number = result.get(0);
        if (number == null || number == 0) {
            return Result.ok(0);
        }
        int count=0;
        //循环遍历
        while (true){
            //让这个数值与1做与运算 得到数值的最后一个比特位
            if ((number & 1)==0){
                //如果为0则表示没有签到 结束
                break;
            }else {
                //如果不为0 则表示签到 计数器加1
                count++;
            }
            //把数字右移一位 抛弃最后一个bit位 继续下一个bit位
            number >>>=1;
        }
        return Result.ok(count);
    }

    @Override
    public Result sign() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        //凭借key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keySuffix;
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //写入redis SELECT key offset 1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }



    @Override
    public Result sendCode(String phone) {
        //判断手机号
        if ( RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail(PHONE_ERROR);
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
       stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY
                + phone, code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码
       log.debug("发送短信验证码成功，验证码：{}", code);
        return Result.ok(code);
    }


    public Result login(LoginFormDTO loginForm) {
        // 获取登录表单中的手机号
        String phone = loginForm.getPhone();
        // 判断手机号是否合法
        if ( RegexUtils.isPhoneInvalid(phone)) {
            // 如果手机号不合法，返回错误信息
            return Result.fail(PHONE_ERROR);
        }
        // 获取登录表单中的验证码
        String code = loginForm.getCode();
        // 从缓存中获取验证码
        Object cacheCode =stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        // 判断缓存中的验证码是否为空或者不等于输入的验证码
        if ( cacheCode == null ||!cacheCode.toString().equals(code)) {
            // 如果验证码不匹配，返回错误信息
//            log.info("cse");
            return Result.fail(CODE_ERROR);
        }
        // 根据手机号查询用户
        User user = query().eq("phone", phone).one();
        // 如果用户不存在，则创建新用户
        if (user == null) {
            user = creatUserWithPhone(phone);
        }
        //BeanUtil.copyProperties(user, UserDTO.class))
        String token= UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        log.info("uuid:{}",token);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        String tokenkey= LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenkey, userMap);
        stringRedisTemplate.expire(tokenkey,LOGIN_USER_TTL,TimeUnit.MINUTES);

        return Result.ok(token);
    }

    private User creatUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
